<template>
  <d2-container :filename="filename" id="CategoryList">
    <template slot="header"><span style="margin-right: 20px;">分类列表</span><el-button @click="onAdd">新增</el-button></template>
    <div class="block">
      <el-tree
        :data="treeData"
        :default-expanded-keys="expendKeys"
        show-checkbox
        node-key="id"
        default-expand-all
        :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}
          <el-tag type="info">状态：{{ data.status }}</el-tag>
          <el-tag>创建时间：{{ data.createTimeStr || '无'}}</el-tag>
          <el-tag type="warning">更新时间：{{ data.updateTimeStr || '无' }}</el-tag></span>
        <span>
          <el-button
            type="text"
            size="mini"
            @click="() => onEdit(data, node)">编辑</el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => onDel(data, node)">删除</el-button>
        </span>
      </span>
      </el-tree>
    </div>

    <d2-crud
      ref="d2Crud"
      :columns="columns"
      :data="listData"
      add-title="编辑分类项"
      :add-template="popTemplate"
      :edit-template="popTemplate"
      :form-options="formOptions"
      :rowHandle="rowHandle"
      @edit-item="onEdit"
      @del-item="onDel"
      @row-add="handleRowAdd"
      @row-edit="handleRowEdit"
      @dialog-cancel="handleDialogCancel">
      <el-button slot="header" style="margin-bottom: 5px" @click="onAdd">新增</el-button>
    </d2-crud>

  </d2-container>
</template>

<script>

import utils from '@/libs/util.gaed'
import categoryUtils from '@/libs/util.category'
import TreeSelect from '@/components/custom-column/tree-select'
const BASE_URL = '/study/categorys'
// let originList = []

export default {
  data () {
    return {
      treeData: [],
      expendKeys: [],
      filename: __filename,
      columns: [
        {
          title: '分类ID',
          key: 'id'
        },
        {
          title: '分类名',
          key: 'name'
        },
        {
          title: '父分类ID',
          key: 'parent_id'
        },
        {
          title: '状态',
          key: 'status'
        },
        {
          title: '分类层级',
          key: 'level'
        },
        {
          title: '创建时间',
          key: 'create_time'
        },
        {
          title: '更新时间',
          key: 'update_time'
        }
      ],
      rowHandle: {
        custom: [
          {
            text: '编辑',
            size: 'small',
            emit: 'edit-item'
          },
          {
            text: '删除',
            type: 'warning',
            size: 'small',
            emit: 'del-item'
          }
        ]
      },
      listData: [], // 列表数据
      pageData: {}, // 分页数据
      popTemplate: {
        name: {
          title: '分类名',
          value: ''
        },
        parent_id: {
          title: '父分类',
          value: '',
          component: {
            name: TreeSelect,
            props: {
              categoryName: '',
              treeData: []
            }
          }
        },
        level: {
          title: '分类层级',
          value: ''
        }
      },
      currentEditId: '',
      formOptions: {
        labelWidth: '80px',
        labelPosition: 'left',
        saveLoading: false
      }
    }
  },
  mounted () {
    this.initList()
  },
  methods: {
    initList () {
      categoryUtils.getCategoryTree().then(data => {
        this.treeData = data
        this.expendKeys = [data[0].id] // 默认将第一级展开
      }).catch(err => {
        console.warn(err)
      })
    },
    /*
    listToTree (rootItem) {
      if (!originList) {
        return null
      }
      // 没有给rootItem的时候，按照parent_id为null的规则找rootItem
      if (!rootItem) {
        originList.some((d, i) => {
          if (!d.parent_id) {
            rootItem = originList.splice(i, 1)
            return true
          }
        })
        if (rootItem.length > 0) {
          rootItem = rootItem[0]
        }
        rootItem.children = rootItem.children || []
      } else {
        // 从originList中剔除rootItem
        originList = originList.filter(d => d.id !== rootItem.id)
      }

      // 找到所有的parent_id为rootItem的id的项，递归查找，返回组装好的，再push到children中
      rootItem.children = originList
        .filter(d => d.parent_id === rootItem.id)
        .map(item => {
          let res = this.listToTree(item)
          return res
        })

      // 从originList中删除已经添加到树结构里的数据
      originList = originList.filter(d => d.parent_id !== rootItem.id)
      return rootItem
    },
    */
    onEdit (row) {
      console.log('编辑：', row)
      this.currentEditId = row.id
      // 重新传递数据
      let formData = {
        name: row.name,
        parent_id: row.parent_id,
        level: row.level
      }
      this.popTemplate.name.value = formData.name // 分类名
      this.popTemplate.parent_id.value = formData.parent_id // 父分类
      this.popTemplate.level.value = formData.level // 分类层级
      this.popTemplate.parent_id.component.props.treeData = this.treeData // 下拉树形组件
      this.$refs.d2Crud.showDialog({
        mode: 'add'
      })
    },
    onAdd () {
      this.currentEditId = ''
      this.popTemplate.parent_id.component.props.treeData = this.treeData
      this.$refs.d2Crud.showDialog({ mode: 'add' })
    },
    // 打开弹窗时自动进行的处理
    handleDialogOpen ({ mode }) {},
    handleRowAdd (dataObj, done) {
      let postData = {
        name: dataObj.name,
        level: dataObj.level,
        parent_id: dataObj.parent_id || 0
      }
      if (this.currentEditId) { // 编辑
        let url = BASE_URL + '/' + this.currentEditId
        utils.editData.call(this, url, postData).then(res => {
          this.initList()
          this.$refs.d2Crud.closeDialog()
          done()
        }).catch(err => {
          console.warn(err)
        })
      } else { // 新增
        utils.addData.call(this, BASE_URL, postData).then(res => {
          this.initList()
          this.$refs.d2Crud.closeDialog()
          done()
        }).catch(err => {
          console.warn(err)
        })
      }
    },
    // 对行进行编辑
    handleRowEdit (dataObj, done) {
      let id = dataObj.row.id
      let url = BASE_URL + '/' + id
      let d = dataObj.row
      let postData = {
        name: d.name,
        level: d.level,
        parent_id: d.parent_id || 0
      }
      utils.editData.call(this, url, postData).then(res => {
        this.initList()
        this.$refs.d2Crud.closeDialog()
        done()
      }).catch(err => {
        console.warn(err)
      })
    },
    onDel (row) {
      this.$alert('确认删除当前分类？', row.title, {
        confirmButtonText: '确定',
        callback: (action) => {
          let url = BASE_URL + '/' + row.id
          utils.deleteData.call(this, url).then(response => {
            this.initList()
          }).catch(err => {
            console.warn(err)
          })
        }
      })
    },
    handleDialogCancel (done) {
      this.$refs.d2Crud.closeDialog()
      done()
    }
  }
}
</script>
<style>
  #CategoryList .el-tree-node__content {
    height: 50px;
  }
  #CategoryList .el-tag {
    margin-left: 10px;
    margin-right: 10px;
  }
  #CategoryList .d2-crud-header,
  #CategoryList .d2-crud-body {
    display: none;
  }
</style>
